
import 'dart:convert';
import 'dart:io';

import 'package:aliyun_vod_upload/model/authInitModel.dart';
import 'package:aliyun_vod_upload/model/vodInfoModel.dart';
import 'package:aliyun_vod_upload/model/vodUploadResultModel.dart';
import 'package:flutter/services.dart';

import 'aliyun_vod_upload_platform_interface.dart';
import 'enum/event.dart';
import 'model/ResumeWithTokenModel.dart';
import 'model/UploadFileInfoModel.dart';
import 'model/stsInitModel.dart';

class AliyunVodUpload {
  static const EventChannel _eventChannel = EventChannel('aliyun_vod_upload/event');

  static addListener({
    OnUploadFinishedListener? onUploadFinishedListener,
    OnUploadFailedListener? onUploadFailedListener,
    OnUploadProgressListener? onUploadProgressListener,
    OnUploadTokenExpiredListener? onUploadTokenExpiredListener,
    OnUploadStartedListener? onUploadStartedListener,
    OnUploadRertyListener? onUploadRertyListener,
    OnUploadRertyResumeListener? onUploadRertyResumeListener,
  }) {
    _eventChannel.receiveBroadcastStream().listen((dynamic result) {
      Map map = json.decode(result);
      if(map['event'] == Event.started.value && onUploadStartedListener != null) {
        onUploadStartedListener(UploadFileInfoModel.fromJson(map['uploadFileInfo']));
      }
      if(map['event'] == Event.progress.value && onUploadProgressListener != null) {
        onUploadProgressListener(UploadFileInfoModel.fromJson(map['uploadFileInfo']), map['uploadedSize'], map['totalSize']);
      }
      if(map['event'] == Event.finished.value && onUploadFinishedListener != null) {
        onUploadFinishedListener(UploadFileInfoModel.fromJson(map['uploadFileInfo']), VodUploadResultModel.fromJson(map['vodUploadResult']));
      }
      if(map['event'] == Event.failed.value && onUploadFailedListener != null) {
        onUploadFailedListener(UploadFileInfoModel.fromJson(map['uploadFileInfo']), map['code'], map['message']);
      }
      if(map['event'] == Event.tokenExpired.value && onUploadTokenExpiredListener != null) {
        onUploadTokenExpiredListener();
      }
    });
  }

  Future<String?> getPlatformVersion() {
    return AliyunVodUploadPlatform.instance.getPlatformVersion();
  }

  // static Future<void> initSTSUpLoader(StsInitModel stsInitModel) {
  //   return AliyunVodUploadPlatform.instance.initSTSUpLoader(stsInitModel);
  // }

  static Future<void> initAuthUpLoader(AuthInitModel authInitModel) {
    return AliyunVodUploadPlatform.instance.initAuthUpLoader(authInitModel);
  }

  static Future<bool> addFile(String filePath, VodInfoModel vodInfoModel) {
    return AliyunVodUploadPlatform.instance.addFile(filePath, vodInfoModel);
  }

  static Future<bool> startUpload() {
    return AliyunVodUploadPlatform.instance.startUpload();
  }

  static Future<void> resumeWithToken(ResumeWithTokenModel resumeWithTokenModel) {
    return AliyunVodUploadPlatform.instance.resumeWithToken(resumeWithTokenModel);
  }

}
